package com.tdx.quick.api.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.tdx.quick.api.utils.DBUtils;
import lombok.extern.slf4j.Slf4j;
import net.hasor.core.ApiBinder;
import net.hasor.core.DimModule;
import net.hasor.dataql.fx.basic.SqlUdfSource;
import net.hasor.dataql.fx.js.JsFragment;
import net.hasor.dataql.fx.python.PythonFragment;
import net.hasor.db.JdbcModule;
import net.hasor.db.Level;
import net.hasor.spring.SpringModule;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Quick Api 配置
 *
 * @author tdx.lq
 * @since 2020/9/25 6:56
 */
@DimModule
@Component
@Slf4j
public class QuickApiConf implements SpringModule {

    @Resource(name = "baseDataSource")
    private DataSource baseDataSource;

    /**
     * 准备JS引擎
     */
    private void prepareJsEngine() throws Throwable {
        JsFragment fragment = new JsFragment();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("msg", "JS");
        String fragmentString = "return 'hello, ' + msg + '!'";
        Object result = fragment.runFragment(null, paramMap, fragmentString);
        log.info("Js Engine init success: " + result);
    }

    /**
     * 准备Python引擎
     */
    private void preparePythonEngine() throws Throwable {
        PythonFragment fragment = new PythonFragment();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("msg", "PYTHON");
        String fragmentString = "\treturn 'hello, ' + msg + '!'";
        Object result = fragment.runFragment(null, paramMap, fragmentString);
        log.info("Python Engine init success: " + result);
    }

    /**
     * 设置 SqlUdf 的连接池
     */
    private void sqlUdfDataSourceSet() {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        DBUtils.dataSourceMap.forEach(dataSourceMap::put);
        SqlUdfSource.dataSourceMap = dataSourceMap;
    }

    public void loadModule(ApiBinder apiBinder) throws Throwable {
        log.warn("初始化 QuickApi, 请稍后...");

        // .DataSource form Spring boot into DataQL
        apiBinder.installModule(new JdbcModule(Level.Full, baseDataSource));

        for (Map.Entry<String, DruidDataSource> entry : DBUtils.dataSourceMap.entrySet())
            apiBinder.installModule(new JdbcModule(Level.Full, entry.getKey(), entry.getValue()));

        // .custom DataQL
        //apiBinder.tryCast(QueryApiBinder.class).loadUdfSource(apiBinder.findClass(DimUdfSource.class));
        //apiBinder.tryCast(QueryApiBinder.class).bindFragment("sql", SqlFragment.class);

        // 初始化JS引擎
        prepareJsEngine();

        // 初始化Python引擎
        preparePythonEngine();

        // 初始化 SqlUdf 工具类的连接池
        sqlUdfDataSourceSet();
    }
}
